package com.dsj.servlet;

import com.dsj.dao.OrderDao;
import com.dsj.dao.OrderItemDao;
import com.dsj.entity.OrderEntity;
import com.dsj.entity.OrderItemEntity;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        OrderDao orderDao = new OrderDao();
        OrderItemDao orderItemDao = new OrderItemDao();

        //会员名
        String curUserName = session.getAttribute("name").toString();
        //请求类型
        String orderAction = request.getParameter("orderAction");

        if(orderAction.equals("orderAbstract")) {  //查看会员的所有订单
            List<OrderEntity> list = new ArrayList<>();
            list = orderDao.selectOrderByName(curUserName);  // 获取用户名下的的订单列表
            request.setAttribute("orderAbstract", list);
            request.getRequestDispatcher("/pages/order/orderList.jsp").forward(request, response);

        }

        if(orderAction.equals("orderDetail")) {  //查看订单详情
            // 从请求参数中获取订单id
            String orderId = request.getParameter("orderId");
            if(orderId!= null) {
                // 根据订单ID从数据库中查询订单基本信息
                OrderEntity orderAbstract = orderDao.selectOrderByOrderId(orderId);
                // 将订单基本信息保存至request对象中
                request.setAttribute("orderAbstract", orderAbstract);

                List<OrderItemEntity> list = new ArrayList<>();
                // 根据订单ID从数据库中查询订单详细信息
                list = orderItemDao.seletOrderDetailById(orderId);
                // 将订单详细信息保存至request对象中
                request.setAttribute("orderItems", list);

                // 通过请求转发的方式，将订单信息及订单详细信息转发至订单详情页处理
                request.getRequestDispatcher("/pages/order/orderItemList.jsp").forward(request, response);

            }
        }

        if(orderAction.equals("orderDelivered")) {  //按用户名及订单是否发货进行查询
            //获取用户名和订单发货状态
            String name = session.getAttribute("name").toString();
            boolean deliverySign = Boolean.parseBoolean(request.getParameter("deliverySign"));

            // 通过用户名和订单发货状态从数据库中查询订单信息
            List<OrderEntity> list = new ArrayList<>();
            list = orderDao.selectOrderByNameAndDeliverySign(name, deliverySign);

            //以前求转发的方式将订单数据传送到订单列表显示页面
            request.setAttribute("orderDeliveryList", list);
            request.getRequestDispatcher("/pages/order/orderListDelivery.jsp").forward(request, response);
        }
    }
}